package com.anysoft.webloader.filter;

import com.alogic.matcher.CommonMatcher;
import com.alogic.matcher.MatcherFactory;
import com.anysoft.util.PropertiesConstants;
import com.anysoft.webloader.FilterConfigProperties;
import com.google.re2j.Matcher;
import com.google.re2j.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用于处理CORS的过滤器
 *
 * @since 1.6.13.31 [20210108 duanyy]
 */
public class CorsFilter implements Filter {
    /**
     * a logger of slf4j
     */
    protected final static Logger LOG = LoggerFactory.getLogger(CorsFilter.class);

    /**
     * 用来提取Origin中域名的正则表达式
     */
    protected static Pattern pattern = Pattern.compile("(\\w+):\\/\\/([^/:]+)(?::(\\d*))?([^#\\?]*)");

    protected boolean corsSupport = false;

    protected CommonMatcher corsMatcher = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        FilterConfigProperties props = new FilterConfigProperties(filterConfig);
        corsSupport = PropertiesConstants.getBoolean(props, "http.cors", corsSupport);
        corsMatcher = MatcherFactory.getMatcher(PropertiesConstants.getString(props,"http.cors.matcher","(wildcard)*"),props);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (corsSupport){
            HttpServletRequest httpReq = (HttpServletRequest)request;
            HttpServletResponse httpResp = (HttpServletResponse)response;
            String origin = httpReq.getHeader("Origin");
            if (StringUtils.isNotEmpty(origin) && corsMatcher != null){
                Matcher matcher = pattern.matcher(origin);
                String domain = origin;
                if (matcher.find()){
                    domain = matcher.group(2);
                }

                if (corsMatcher.isMatch(domain)) {
                    httpResp.setHeader("Access-Control-Allow-Origin", origin);
                    httpResp.setHeader("Access-Control-Allow-Credentials", "true");
                }
            }
        }
        chain.doFilter(request, response);
    }


    @Override
    public void destroy() {

    }
}